<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog system-user-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="dataList.ProcessTask"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      @closed="closeDialog"
    >
      <el-divider class="el-divider-specail" content-position="left"
        ><span>{{ dataList.EquipInfo }}</span>
      </el-divider>
      <el-table
        :data="[formData.deviceDto]"
        element-loading-text="Loading"
        fit
        highlight-current-row
        height="80px"
      >
        <el-table-column :label="dataList.DeviceNumber">
          <template slot-scope="scope">
            {{ scope.row.num }}
          </template>
        </el-table-column>
        <el-table-column
          :label="
            $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
          "
        >
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceSpecifications">
          <template slot-scope="scope">
            {{ scope.row.specifications }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceStatus">
          <template slot-scope="scope">
            {{ scope.row.statusName }}
          </template>
        </el-table-column>
        <el-table-column
          :label="
            $i18n.locale === 'en'
              ? dataList.eDeviceStorageAddress
              : dataList.DeviceStorageAddress
          "
        >
          <template slot-scope="scope">
            {{ scope.row.storageAddress }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DevicePersonResponsibleId">
          <template slot-scope="scope">
            {{ scope.row.personResponsibleName }}
          </template>
        </el-table-column>
      </el-table>
      <el-divider class="el-divider-specail" content-position="left"
        ><span>{{ dataList.InspectionPlan }}</span>
      </el-divider>
      <el-table
        :data="[formData]"
        element-loading-text="Loading"
        fit
        highlight-current-row
        height="80px"
      >
        <el-table-column :label="dataList.InspectionTarget">
          <template slot-scope="scope">
            {{ scope.row.verificationObject }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.InspectionMethod">
          <template slot-scope="scope">
            {{ scope.row.verificationWay }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.InspectionProcedure">
          <template slot-scope="scope">
            {{ scope.row.verificationMethod }}
          </template>
        </el-table-column>
      </el-table>

      <el-form
        ref="formData"
        class="base-pipeline-layout system-user-form"
        label-width="100px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-divider class="el-divider-specail" content-position="left"
          ><span>{{ dataList.InspectionRecord }}</span>
        </el-divider>
        <el-form-item
          style="width: 100%"
          :label="dataList.Inspector"
          :label-width="formLabelWidth"
          prop="verificationPersonId"
          :error="errorMsg.verificationPersonId"
        >
          <div style="width: 30%; float: left">
            <UserDropDownList
              :value="formData.verificationPersonId"
              :return-objct.sync="returnObjct"
              @input="borrowPersonChange"
            />
          </div>
        </el-form-item>
        <el-form-item
          style="width: 100%"
          :label="dataList.InspectionTime"
          :label-width="formLabelWidth"
          prop="verificationDate"
          :error="errorMsg.verificationDate"
        >
          <el-date-picker
            v-model="formData.verificationDate"
            style="width: 30%; float: left"
            type="date"
            :placeholder="dataList.SelectDateTime"
            value-format="yyyy-MM-dd"
            @change="verificationDateChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          :label="dataList.RecordedContent"
          style="width: 100%"
          :label-width="formLabelWidth"
          prop="content"
          :error="errorMsg.content"
        >
          <div>
            <TinyEditor v-model="formData.content"></TinyEditor>
          </div>
        </el-form-item>

        <el-form-item
          :label="dataList.DeviceImg"
          prop="imgArray"
          style="width: 100% !important; margin-top: 84px"
        >
          <div class="deviceAddDialogImg">
            <BaseMultipleUpload
              key="BaseUpload"
              ref="BaseUpload"
              v-model="formData.imgArray"
              business-type="110"
              :file-size="5120"
              :limit="3"
              :style-c-s-s="styleCSS"
              :multiple="true"
              :show-file-list="true"
              :list-type="'picture-card'"
              style="
                display: flex;
                align-items: start;
                padding-left: 10px;
                flex-direction: column;
              "
              :tip="dataList.DeviceImgTip('jpg，jpeg，png,gif,bmp,tiff')"
              :accept="'.jpeg,.jpg,.png,.gif,.bmp,.tiff'"
            />
          </div>
        </el-form-item>

        <el-form-item
          :label="dataList.DeviceAnnex"
          prop="fileArray"
          style="width: 100% !important"
        >
          <div class="deviceAddDialogFile">
            <BaseUploadFile
              key="BaseUploadFile"
              ref="BaseUploadFile"
              v-model="formData.fileArray"
              business-type="120"
              :file-size="10240"
              :limit="10"
              :multiple="true"
              style="display: flex; align-items: center; padding-left: 10px"
              :tip-text="`${dataList.UploadTypeAs}pdf、doc、docx、xls、xlsx、zip、rar、apk;${dataList.DeviceAnnexTip}`"
            />
          </div>
        </el-form-item>

        <el-divider class="el-divider-specail" content-position="left"
          ><span>{{ dataList.InspectionResult2 }}</span>
        </el-divider>

        <el-form-item
          :label="dataList.InspectionCon"
          :label-width="formLabelWidth"
          prop="conclusionEnum"
          :error="errorMsg.conclusionEnum"
        >
          <el-select
            v-model="formData.conclusionEnum"
            :placeholder="dataList.Placeholder"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          style="width: 100%"
          :label="dataList.ConclusionReason"
          :label-width="formLabelWidth"
          prop="conclusionReason"
          :error="errorMsg.conclusionReason"
        >
          <el-input
            v-model="formData.conclusionReason"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="dataList.EquipStatusAfterInspec"
          :label-width="formLabelWidth"
          prop="deviceStatus"
          :error="errorMsg.deviceStatus"
        >
          <dic-drop-down-list
            v-model="formData.deviceStatus"
            dict-code="deviceStatusList"
            :display-text="displayText"
          ></dic-drop-down-list>
        </el-form-item>
        <el-form-item
          style="width: 100%"
          :label="dataList.NextInspecTime"
          :label-width="formLabelWidth"
          prop="nextCheckDate"
          :error="errorMsg.verificationDateNext"
        >
          <el-date-picker
            v-model="formData.nextCheckDate"
            style="width: 30%; float: left"
            type="date"
            :placeholder="dataList.SelectDateTime"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')">{{
          btn.Save
        }}</el-button>
        <el-button
          type="primary"
          style="width: 100px"
          @click="onSubmitAndValidate('formData')"
          >{{ btn.SaveAndSubmit }}</el-button
        >
        <el-button @click="cancel">{{ btn.Cancel }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getList,
  updateAndVerifyStart,
  update,
} from "../../../api/DeviceVerificationTask.js";
import UserDropDownList from "../../../components/UserDropDownList.vue";
import DicDropDownList from "../../../components/DicDropDownList.vue";
import TinyEditor from "../../../components/TinyEditor.vue";
import { conclusion, normal } from "../../../utils/const";
import { getDateByName, formatTime } from "../../../utils/time";
import { mapGetters } from "vuex";

export default {
  name: "DeviceVerificationTaskDisposeDialog",
  components: { UserDropDownList, DicDropDownList, TinyEditor },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: "",
    },
  },

  data() {
    return {
      isAll: false,
      displayText: [
        i18n.t("ModuleDevice.Device.Normal"),
        i18n.t("ModuleDevice.Device.Fault"),
      ],
      options: conclusion,
      styleCSS: "text-align:left",
      verificationObjectList: [],
      verificationWayList: [],
      returnObjct: true,
      choiceDeviceVisible: false,
      list: [],
      listDeviceVerification: [],
      loading: false,
      formLabelWidth: "120px",
      formData: {
        conclusionEnum: 0,
        verificationPersonId: this.$store.getters.currentUserId,
        verificationDate: new Date(),
        content: "",
        imgArray: [],
        fileArray: [],
        conclusion: 10,
        verificationDateNext: null,
        deviceStatus: normal,
      },
      errorMsg: {
        verificationPersonId: "",
        verificationDate: "",
        content: "",
        imgArray: "",
        fileArray: "",
        conclusion: "",
        verificationDateNext: "",
        deviceStatus: "",
      },
      formDataRules: {
        verificationPersonId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        verificationDate: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        conclusionEnum: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        deviceStatus: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["fileDomain", "fileBucket"]),
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },
  watch: {},
  created() {
    this.initData();
  },
  methods: {
    formatTime,
    verificationDateChange() {
      if (this.formData.type === 10) {
        if (this.formData.deviceVerificationPlanInfoDto != null) {
          if (this.formData.deviceVerificationPlanInfoDto.cycle !== "") {
            this.formData.nextCheckDate = getDateByName(
              this.formData.verificationDate,
              this.formData.deviceVerificationPlanInfoDto.cycle,
              this.formData.deviceVerificationPlanInfoDto.cycleName
            );
          }
        }
      }
    },
    getDicValue(id, name) {
      this.formData.deviceStatus = id;
    },
    initData() {
      this.loading = true;
      getList({ id: this.editId })
        .then((res) => {
          if (res.data.dataList != null && res.data.dataList.length > 0) {
            this.formData = res.data.dataList[0];

            this.formData.conclusionEnum =
              this.formData.conclusion === 0 ? "" : this.formData.conclusion;
            this.formData.verificationPersonId =
              this.$store.getters.currentUserId;
            if (
              this.formData.verificationDate === "" ||
              this.formData.verificationDate.indexOf("1900") !== -1
            ) {
              this.formData.verificationDate = new Date();
            }
            if (
              this.formData.deviceStatus === 0 ||
              this.formData.deviceStatus === "0" ||
              this.formData.deviceStatus == null
            ) {
              this.formData.deviceStatus = normal;
            }
            if (
              this.formData.nextCheckDate === "" ||
              this.formData.nextCheckDate.indexOf("1900") !== -1
            ) {
              if (this.formData.type === 20) {
                this.formData.nextCheckDate = null;
              } else {
                if (this.formData.deviceVerificationPlanInfoDto != null) {
                  if (
                    this.formData.deviceVerificationPlanInfoDto.cycle !== ""
                  ) {
                    this.formData.nextCheckDate = getDateByName(
                      this.formData.verificationDate,
                      this.formData.deviceVerificationPlanInfoDto.cycle,
                      this.formData.deviceVerificationPlanInfoDto.cycleName
                    );
                  }
                }
              }
            }
            this.formData.fileArray = [];
            this.formData.sysBusinessFileWarehouseList.map((item) => {
              var obj = item;
              obj.name = item.originalFileName;
              // obj.url = `${this.$baseProtocol}//${this.fileDomain}/${this.fileBucket}/${item.filePath}`;
              obj.url = `${item.filePath}`;
              this.formData.fileArray.push(obj);
            });
            this.formData.imgArray = [];

            this.formData.sysBusinessImgWarehouseList.map((item) => {
              var obj = item;
              obj.name = item.originalFileName;
              // obj.url = `${this.$baseProtocol}//${this.fileDomain}/${this.fileBucket}/${item.filePath}`;
              obj.url = `${item.filePath}`;
              obj.imgUrl = item.filePath;
              this.formData.imgArray.push(obj);
            });
          }

          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    wayInputChange(index, val) {
      this.verificationWayList[index].label = val;
    },
    objectInputChange(index, val) {
      this.verificationObjectList[index].label = val;
    },
    borrowPersonChange(val) {
      this.formData.verificationPersonId = val.value;
      this.formData.verificationPersonName = val.label;
    },
    cancel() {
      this.$emit("update:dialogFormVisible", false);
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },
    onSubmit() {
      // 图片
      this.formData.sysBusinessImgWarehouseList = [];
      if (this.formData.imgArray !== undefined) {
        this.formData.imgArray.forEach((item) => {
          var obj = {};
          obj.fileTpyeCode = 1;
          obj.originalFileName = item.originalFileName;
          obj.storageFileName = item.storageFileName;
          obj.filePath = item.filePath;
          this.formData.sysBusinessImgWarehouseList.push(obj);
        });
      }

      // 附件
      this.formData.sysBusinessFileWarehouseList = [];
      if (this.formData.fileArray !== undefined) {
        this.formData.fileArray.forEach((item) => {
          var obj = {};
          obj.fileTpyeCode = 2;
          obj.originalFileName = item.name;
          obj.storageFileName = "";
          obj.filePath = item.url2;
          this.formData.sysBusinessFileWarehouseList.push(obj);
        });
      }
      this.formData.verificationTypeEnum = this.formData.type;
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);

          update(this.formData)
            .then((res) => {
              if (res.code === 200) {
                this.closeDialog();
              } else {
                this.showValidateMsgCheck(res);
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    onSubmitAndValidate() {
      // 图片
      this.formData.sysBusinessImgWarehouseList = [];
      if (this.formData.imgArray !== undefined) {
        this.formData.imgArray.forEach((item) => {
          var obj = {};
          obj.fileTpyeCode = 1;
          obj.originalFileName = item.originalFileName;
          obj.storageFileName = item.storageFileName;
          obj.filePath = item.filePath;
          this.formData.sysBusinessImgWarehouseList.push(obj);
        });
      }
      // 附件
      this.formData.sysBusinessFileWarehouseList = [];
      if (this.formData.fileArray !== undefined) {
        this.formData.fileArray.forEach((item) => {
          var obj = {};
          obj.fileTpyeCode = 2;
          obj.originalFileName = item.name;
          obj.storageFileName = "";
          obj.filePath = item.url2;
          this.formData.sysBusinessFileWarehouseList.push(obj);
        });
      }
      this.formData.verificationTypeEnum = this.formData.type;
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);

          updateAndVerifyStart(this.formData)
            .then((res) => {
              if (res.code === 200) {
                this.closeDialog();
              } else {
                this.showValidateMsgCheck(res);
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("verificationDate", this.errorMsg, res.msg);
        this.Helper.showValidateMsg(
          "verificationPersonId",
          this.errorMsg,
          res.msg
        );
        this.Helper.showValidateMsg("conclusionEnum", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("deviceStatus", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
<style scoped lang="scss">
.deviceAddDialogFile {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  height: 150px;
  ::v-deep.base-upload {
    text-align: left;
    display: flex;
    flex-direction: column;
    padding-top: 10px;
    width: 100%;
  }
  ::v-deep .el-upload-list__item {
    width: 50%;
  }
  ::v-deep .el-upload {
    text-align: left;
  }
  ::v-deep .el-upload-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    overflow-y: auto;
  }
  ::v-deep .el-upload__tip {
    color: red;
  }
}
.deviceAddDialogImg {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  height: 150px;
  ::v-deep .el-upload--picture-card {
    width: 116px;
    height: 88px;
    border: 1px solid #dcdfe6;
  }
  ::v-deep .el-upload-list__item {
    width: 116px;
    height: 88px;
    border: 1px solid #dcdfe6;
  }
  ::v-deep.el-upload {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  ::v-deep .tip-text {
    color: red !important;
    font-size: 12px;
  }
  ::v-deep .el-upload-list--picture-card {
    margin-left: 10px;
  }

  ::v-deep .base-upload {
    display: flex;
    flex-direction: row-reverse;
    margin-top: 10px;
  }
}
</style>
